#!/usr/bin/env python
#vhost autocheck date 20180301
import os
import sys
import hashlib
import sqlite3
import subprocess
import urllib2

def md5hex(FilePath):
    if os.path.exists(FilePath):
        with open(FilePath,'rb') as f:
            md5obj = hashlib.md5()
            md5obj.update(f.read())
            md5value = md5obj.hexdigest()
            return md5value
    else:
        return value


if __name__ == "__main__":
    
    security_code='CKVHOST2015'
    id_cfg = '/root/Autocheck/id.cfg'
    #GET id
    if os.path.exists(id_cfg):
        fn = open(id_cfg,'r')
        for line in fn:
            if 'server_id' in line:
                 tmp = line.split("=")
                 if tmp[1].strip() != '':
                     svr_id = tmp[1].strip()
                 else:
                     exit()
        fn.close()

    else:

        url =  'http://databackup.cndns.com/backup-report/report_id.php'
        conn = urllib2.urlopen(url,timeout=10)
        str=conn.read()
        tmp = str.split("=")

        if tmp[1].strip() != '':
            id = tmp[1].strip()
        else:
            exit()

        fn = open('/root/Autocheck/id.cfg','w')
        fn.write(str)
        fn.close()
        conn.close()

    check_list = {'cron':'/var/spool/cron/root','ssh':'/etc/ssh/sshd_config','iptables':'/root/Autocheck/iptables.tmp','nginx.conf':'/usr/local/tengine/conf/nginx.conf'}#
    db_path="/root/Autocheck/md5.db"
    
    if( len(sys.argv) == 2):
        conn = sqlite3.connect(db_path)
        c = conn.cursor()
        if(sys.argv[1] == "init"):
            del_table='DROP TABLE IF EXISTS md5_list'
            c.execute(del_table)
            create_table='CREATE TABLE IF NOT EXISTS md5_list (NAME TEXT PRIMARY KEY NOT NULL,MD5 TEXT NOT NULL);'
            c.execute(create_table)

            #iptables
            os.system('/sbin/iptables -L -n|/bin/grep -v -E "REJECT|RETURN" >/root/Autocheck/iptables.tmp')
               
            for key,value in check_list.items():
                name = key
                fmd5= md5hex(value)
                sql="INSERT INTO md5_list VALUES ('%s','%s')" % (name,fmd5)
                c.execute(sql)

            conn.commit()

            

            

        if(sys.argv[1] == "check"):
            #security code
            f_md5=md5hex(db_path)
            code=f_md5+security_code
            m1 = hashlib.md5()
            m1.update(code)
            svr_token = m1.hexdigest()
		
            #check
            bad_service=''
            for key,value in check_list.items():
                
                if( key == 'iptables' ):
                    os.system('/sbin/iptables -L -n|/bin/grep -v -E "REJECT|RETURN" >/root/Autocheck/iptables.tmp')
                
                sql="SELECT * FROM md5_list where NAME='"+key+"'"
                
                cursor = c.execute(sql)
                for row in cursor:
                    fmd5= md5hex(value)
                    if(fmd5 == row[1]):
                        print key + " sql:" + row[1] + " check:" + fmd5 +"  OK"
                    else:
                        print key + " sql:" + row[1] + " check:" + fmd5+"  CHANGED"
                        if( bad_service == ''):
                            bad_service = key
                        else:
                            bad_service = key + "|" + bad_service
                
            #report to server
            url = 'http://databackup.cndns.com/auto_ck/check_api.php?type=vhost&token=%s&svr_id=%s&f_md5=%s&bad_service=%s' % (svr_token,svr_id,f_md5,bad_service)

            try:
                rep_conn = urllib2.Request(url)
                p = urllib2.urlopen(rep_conn,timeout=60)
                print url
                print 'report ok'
            except Exception,e:
                print e,url
                print 'ERROR: job report error'
            p.close()
                
	#close sqlite connection    
        conn.close()
            
